<template>
  <c-form-dialog
    ref="form"
    :visible.sync="innerVisible"
    :table-name="tableName"
    :form-items="formItems"
    :form-data="formData"
    :before-save="handleBeforeSave"
    :table-id="tableId"
    @success="onsuccess"
    @close="handleClose"
    label-width="140px"
    :title="tableId ? '修改主体信息' : '新增主体'"
  ></c-form-dialog>
</template>

<script>
import { enumCompanyType, enumCompanyLevel } from '@/gov/plugins/enum'
import SelectAddress from '@/components/select/SelectAddress'
import { phoneValidator } from '@/common/plugins/validator'
import { mapGetters } from 'vuex'
import { idCardValidate, licenseValidate } from '@vimi/utils-tool'
import SelectCustomer, { fields } from '@/gov/components/select/SelectCustomer'
export default {
  props: {
    visible: Boolean,
    formData: {
      type: Object,
      default: () => ({}),
    },
    pageId: String,
    pageName: String,
    tableId: String,
  },
  data() {
    const registerValidator = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入统一信用代码'))
      } else if (!licenseValidate(value)) {
        callback(new Error('统一信用代码格式错误!'))
      } else {
        const params = {
          index: 1,
          size: 1,
          'submit_type.eq': 1,
          'customer_type.eq': 1,
          'project_type_id.eq': this.pageId,
          'register_no.eq': value,
        }
        const [res] = await this.fetchData(params)
        const data = (res && res.data && res.data.data) || []
        if (data.length && data[0].datum_customer_info_warehouse_id !== this.tableId) {
          callback(new Error('统一信用代码已存在'))
        } else {
          callback()
        }
      }
    }
    const idCardValidator = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入身份证号码'))
      } else if (!idCardValidate(value)) {
        callback(new Error('身份证号错误!'))
      } else {
        if (+this.customer_type !== 2) {
          callback()
        }
        const params = {
          index: 1,
          size: 1,
          'customer_type.eq': 2,
          'submit_type.eq': 1,
          'project_type_id.eq': this.pageId,
          'id_card.eq': value,
        }
        const [res] = await this.fetchData(params)
        const data = (res && res.data && res.data.data) || []
        if (data.length && data[0].datum_customer_info_warehouse_id !== this.tableId) {
          callback(new Error('身份证号已存在!'))
        } else {
          callback()
        }
      }
    }
    return {
      innerVisible: false,
      formItems: [
        {
          tag: SelectCustomer,
          itemAttrs: {
            label: '企业名称',
            rules: { required: true, message: '请输入企业名称', trigger: 'blur' },
          },
          attrs: {
            key: 'customer_name',
            value: '',
            placeholder: '企业名称',
            class: 'form-control-ml',
            industry: true,
          },
          listeners: {
            select: customer => {
              fields.forEach(key => {
                this.$refs.form.setAttrs(key, { value: customer[key] })
              })
            },
          },
        },
        {
          tag: SelectAddress,
          itemAttrs: {
            label: '机构地址',
            rules: { required: true, message: '请选择机构地址', trigger: 'change' },
          },
          attrs: { key: 'address_code', value: '', class: 'form-control-ml', autoTop: true },
          listeners: {
            select: label => {
              this.$refs.form.setAttrs('address', { value: label })
            },
          },
        },
        {
          tag: 'input',
          attrs: { key: 'address' },
          ifShow: false,
        },
        {
          tag: 'input',
          itemAttrs: { label: '详细地址' },
          attrs: { key: 'address_detail', value: '', placeholder: '请输入地址' },
        },
        {
          tag: 'select',
          itemAttrs: {
            label: '企业类型',
            rules: [{ required: true, message: '请选择企业类型', trigger: 'change' }],
          },
          attrs: { clearable: false, key: 'org_class', options: enumCompanyType },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '营业证号',
            rules: [{ required: true, validator: registerValidator, trigger: ['change', 'blur'] }],
          },
          attrs: { key: 'register_no', value: '', placeholder: '营业证号' },
          ifRender: model => {
            const type = !['org_farmer', 'org_farm', 'org_large_breed'].includes(model.org_class)
            this.customer_type = type ? 1 : 2
            return type
          },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '企业类型',
          },
          attrs: { key: 'org_class_name', value: '', placeholder: '企业类型' },
          ifShow: false,
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '生产环节',
            rules: { required: true, message: '请输入生产环节', trigger: 'blur' },
          },
          attrs: { key: 'parent_main_business', value: '', placeholder: '生产环节' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '主营业务',
            rules: { required: true, message: '请输入主营业务', trigger: 'blur' },
          },
          attrs: { key: 'main_business', value: '', placeholder: '主营业务' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '产业规模',
            rules: { required: true, message: '请输入产业规模', trigger: 'blur' },
          },
          attrs: { key: 'scale', value: '', placeholder: '产业规模' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '经营年限',
            rules: [{ required: true, message: '请输入经营年限', trigger: 'blur' }],
          },
          attrs: { key: 'bussiness_years', value: '' },
          tagSlots: [{ name: 'append', slot: '年' }],
          directives: [
            {
              name: 'input-number',
              value: {
                min: 0,
                max: 200,
                fixed: 2,
                onMin: () => this.$message.error('不能小于0'),
              },
            },
          ],
        },
        {
          tag: 'select',
          itemAttrs: {
            label: '级别',
            rules: [{ required: true, message: '请选择企业级别', trigger: 'change' }],
          },
          attrs: { clearable: false, key: 'lever_type', options: enumCompanyLevel },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '负责人',
            rules: { required: true, message: '请输入负责人名称', trigger: 'blur' },
          },
          attrs: { key: 'corp_name', value: '', placeholder: '负责人名称' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '身份证号',
            rules: [{ required: true, validator: idCardValidator, trigger: ['change', 'blur'] }],
          },
          attrs: { key: 'id_card', value: '', placeholder: '请输入身份证号' },
        },
        {
          tag: 'input',
          itemAttrs: {
            label: '联系电话',
            rules: [
              { required: true, message: '请输入手机号码', trigger: 'blur' },
              { validator: phoneValidator, message: '请输入正确的手机号码', trigger: 'blur' },
            ],
          },
          attrs: { key: 'mobile_no', value: '', placeholder: '联系电话' },
        },
      ],
      tableName: 'datum_customer_info_warehouse',
      customer_type: '',
    }
  },
  watch: {
    visible(val) {
      this.innerVisible = val
    },
  },
  computed: {
    ...mapGetters(['']),
  },
  created() {},
  methods: {
    fetchData(params) {
      return this.$utils.promise(this.$api.getData(this.$serviceName, this.tableName, params))
    },
    handleBeforeSave(data) {
      const type = !['org_farmer', 'org_farm', 'org_large_breed'].includes(data.org_class)
      data.customer_type = type ? 1 : 2
      data.submit_type = 1
      data.project_type_id = this.pageId
      data.project_type_name = this.pageName
      if (!type) {
        data.family_address = data.address
        data.family_address_code = data.address_code
        data.family_address_code_detail = data.address_detail
      }
      return data
    },
    handleClose() {
      this.innerVisible = false
      this.$emit('update:visible', false)
    },
    onsuccess() {
      this.$emit('success', true)
    },
  },
}
</script>
<style lang="scss" scoped></style>
